/********************************************************************************
 * Project Name		[JavaEE_JDBC]
 * File Name     	[CommonDao.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package dao.impl5;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import utils.jdbc.JdbcUtilsEnhanced;

/**
 * 一个通用的Dao, 不依赖于任何一个接口[DBUtils实现]
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class CommonDao {

	private QueryRunner queryRunner = new QueryRunner();

	/**
	 * 执行Insert/Update/Delete操作
	 * 
	 * @param sql
	 * @param parameters
	 * @throws SQLException
	 */
	public int update(String sql, Object... parameters) throws SQLException {
		Connection connection = JdbcUtilsEnhanced.getConnection();
		return queryRunner.update(connection, sql, parameters);
	}

	/**
	 * 获得查询的结果集合
	 * 
	 * @param classType
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws SQLException
	 */
	public <T> List<T> list(Class<T> classType, String sql, Object... parameters) throws SQLException {
		Connection connection = JdbcUtilsEnhanced.getConnection();
		return queryRunner.query(connection, sql, new BeanListHandler<>(classType), parameters);
	}

	/**
	 * 获得唯一一条记录
	 * 
	 * @param classType
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws SQLException
	 */
	public <T> T uniqueResult(Class<T> classType, String sql, Object... parameters) throws SQLException {
		Connection connection = JdbcUtilsEnhanced.getConnection();
		return queryRunner.query(connection, sql, new BeanHandler<>(classType), parameters);
	}

	/**
	 * 获得某条记录某个字段的值, 或一个统计值(count(),avg())
	 * 
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws SQLException
	 */
	public <E> E getValueForSingleColumn(String sql, Object... parameters) throws SQLException {
		Connection connection = JdbcUtilsEnhanced.getConnection();
		return queryRunner.query(connection, sql, new ScalarHandler<>(), parameters);
	}

	/**
	 * 批处理操作
	 * 
	 * @param sql
	 * @param parameters
	 * @throws SQLException
	 */
	public void batch(String sql, Object[]... parameters) throws SQLException {
		Connection connection = JdbcUtilsEnhanced.getConnection();
		queryRunner.batch(connection, sql, parameters);
	}
}
